package com.qianfeng.lingshijia;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;



/**
 * Created by Administrator on 2016/1/13.
 */
public class PersonMessageActivity extends BaseActivity {
    private FrameLayout frameLayout;
   // private RelativeLayout frameLayout;
    private ImageView faceImage;

    private  Bitmap headImage;
    private  static String path="/sdcard/myHead";//图片路径

    private String[] items = new String[]{"选择本地图片", "拍照"};
    //头像名称设置
    private static final String IMAGE_FILE_NAME = "faceImage.jpg";
    //请求码
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESULT_REQUEST_CODE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题
        setContentView(R.layout.person_message);

        frameLayout = (FrameLayout) findViewById(R.id.id_face);
        faceImage = (ImageView) findViewById(R.id.id_face_image);
        Bitmap bt= BitmapFactory.decodeFile(path+IMAGE_FILE_NAME);//从Sd中找头像，转换成Bitmap
        if (bt !=null) {
            @SuppressWarnings("deprecation")
            Drawable drawable=new BitmapDrawable(bt);
            faceImage.setImageDrawable(drawable);
        }else{
            //如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
        }

        frameLayout.setOnClickListener(listener);

    }

    private View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showDialog();
        }
    };

    /**
     * 显示选择对话框
     */
    private void showDialog() {

        new AlertDialog.Builder(this)
                .setTitle("设置头像")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                //从照片里面取图片
                                Intent intentFromGallery = new Intent(Intent.ACTION_PICK,null);
                                intentFromGallery.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                        "image/*"); // 设置文件类型
                                startActivityForResult(intentFromGallery,
                                        IMAGE_REQUEST_CODE);
                                break;
                            case 1:
                                //调用相机拍照
                                Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(
                                        Environment.getExternalStorageDirectory(),
                                        IMAGE_FILE_NAME
                                )));
                                startActivityForResult(intentFromCapture,
                                        CAMERA_REQUEST_CODE);
                                break;
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 0:
                if(resultCode == RESULT_OK){
                    //裁剪图片
                    startPhotoZoom(data.getData());
                }
                break;
            case 1:
                if(resultCode == RESULT_OK){
                    File temp=new File(Environment.getExternalStorageDirectory()+IMAGE_FILE_NAME);
                    startPhotoZoom(Uri.fromFile(temp));//裁剪图片
                }
                break;
            case 2:
                if(data !=null){
                    Bundle extras=data.getExtras();
                    headImage=extras.getParcelable("data");
                    if(headImage !=null){
                        //保存在SD卡中
                        setPicToView(headImage);
                        faceImage.setImageBitmap(headImage);//用ImageView显示出来

                    }
                }
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     *
     */
    private void getImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(photo);
            faceImage.setImageDrawable(drawable);
        }
    }

    public  void setPicToView(Bitmap mBitmap){
        String sdStatus=Environment.getExternalStorageState();
        if(!sdStatus.equals(Environment.MEDIA_MOUNTED)){
            return;
        }
        FileOutputStream b=null;
        File file=new File(path);
        String  fileName=path+IMAGE_FILE_NAME;
        try{
            b=new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG,100,b);
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }finally {
            try {
                //关闭流
                b.flush();
                b.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }

    }
        public void back(View view) {
        startActivity(new Intent(this, PersonSetActivity.class));
            finish();
    }


}

